﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Web.Caching;
using System.Xml;

namespace ORM
{
    public class XmlHelper
    {
        private readonly string _cachekey = "db.Config";
        /// <summary>
        /// 创建目录
        /// </summary>
        /// <param name="name">名称</param>
        /// <returns>创建是否成功</returns>
        [DllImport("dbgHelp", SetLastError = true)]
        private static extern bool MakeSureDirectoryPathExists(string name);
        internal XmlHelper()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + @"config\";
            MakeSureDirectoryPathExists(path);
            string sPath = path + @"\db.config";
            if (!File.Exists(sPath))
            {
                using (StreamWriter write = new StreamWriter(sPath, true, Encoding.UTF8))
                {
                    write.Write(GetXmlContent());
                    write.Close();                   
                }
                return;
            }
            LoadDb(sPath);
        }

        internal Dictionary<string, string> GetLoadDb()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + @"config/db.config";
            return LoadDb(path);
        }

        internal string GetConnstringByAilas(string alias)
        {
            string result = "";
            Dictionary<string, string> list = GetLoadDb();
            if (null == list) return result;
            
            if (String.IsNullOrEmpty(alias))
            {
                foreach (KeyValuePair<string, string> pair in list)
                {
                    result = pair.Value;
                    break;
                }
            }
            if (alias != null)
            {
                if (!list.ContainsKey(alias)) return result;
                result = list[alias];
            }
            return result;
        }

        private Dictionary<string, string> LoadDb(string path)
        {
            object obj = CacheHelper.GetCache(_cachekey);
            if (null != obj) return (Dictionary<string, string>)obj;

            Dictionary<string, string> connList = null;
            try
            {
                XmlDocument document = new XmlDocument();
                document.Load(path);
                XmlNodeList nodelist = document.SelectNodes("/database/instance");
                if (null == nodelist) return null;

                connList = new Dictionary<string, string>();;

                string alias = "";
                string connectstring = "";
                XmlElement element = null;
                foreach (XmlNode node in nodelist)
                {
                    element = (XmlElement)node;
                    alias = element.GetAttribute("alias");
                    connectstring = element.GetAttribute("connectstring");
                    if (0 != String.Compare(connectstring, "链接字符串") && !String.IsNullOrEmpty(connectstring) && !String.IsNullOrEmpty(alias))
                    {
                        if (!connectstring.Contains(alias))
                        {
                            connList.Add(alias, connectstring);
                        }
                    }
                }
                if (connList.Count > 0) CacheHelper.SetCache(_cachekey, connList, new CacheDependency(path));
            }
            catch (Exception)
            {
                return null;
            }
            return connList;
        }

        private string GetXmlContent()
        {
            StringBuilder xml = new StringBuilder("");
            xml.Append("<?xml version=\"1.0\" ?>\n");
            xml.Append("<database>\n");
            xml.Append("   <instance alias=\"user\" connectstring=\"链接字符串\" />\n");
            xml.Append("   <instance alias=\"other\" connectstring=\"\" />\n");
            xml.Append("   <!--其他数据库-->\n");
            xml.Append("</database>\n");
            return xml.ToString();
        }

        public void XmlHelper2()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "//config/";
            MakeSureDirectoryPathExists(path);
            if (!File.Exists(path + "db.config"))
            {
                File.Create(path + "/db.config");
            }

        }
    }
}
